<template>
  <div id="wrapper">   
    <div id="task-src">
      <div class="task-wrap hidden">
        <el-tabs v-model="currentTab" type="card" @tab-click="handleClick">
          <el-tab-pane label="日期" name="first">
            <el-date-picker
              v-model="day"
              type="month"
              format="yyyy-MM"
              placeholder="日期"
              style="width:115px">
            </el-date-picker>
            <el-date-picker
              v-model="week"
              type="week"
              format="WW周"
              placeholder="周"
              style="width:80px">
            </el-date-picker>
            <el-button type="primary" style="width:200px;margin-top:5px" @click="getWeekTasks">搜索</el-button>
          </el-tab-pane>
          <el-tab-pane label="搜索" name="second">
            <div>
              <el-input style="width:90%" placeholder="请输入内容" v-model="searchTxt">
              </el-input>
              <el-button type="primary" style="width:190px;margin-top:5px" @click="searchTasks">搜索</el-button>
            </div>
          </el-tab-pane>
          <el-tab-pane label="收藏" name="third"></el-tab-pane>
          <el-tab-pane label="任务车" name="fourth"></el-tab-pane>
        </el-tabs>
        <div class="src-task-wrap">
          <ul class="task-list" id="src-task-list">
            <li class="task-item" v-for="(item, index) in currentTasks" :data-index="index">
              <a href="javascript:void(0);" :data-index="index">{{ item.title }}</a>
            </li>
          </ul>
        </div>
      </div>
      <a href="javascript:void(0)" class="bt-close-open" @click="closeOpen">
        <i class="el-icon-d-arrow-right"></i>
      </a>
      <div class="sel-task-wrap">
        <div class="sel-title">
          <p class="sel-title-text">
          <!--<a href="javascript:void(0)" id="close-sel"><i class="el-icon-close"></i></a>
          &nbsp;&nbsp;-->任务列表&nbsp;&nbsp;
            <a href="javascript:void(0)" class="bt-switch-wrap" id="bt-switch" @click="putTasks">
              <i class="el-icon-d-arrow-right"></i>
            </a>
          </p>
        </div>
        <ul class="task-list" id="sel-task-list">
            <li class="task-item" v-for="(item, index) in selectedTasks" :data-index="index">
              <a href="javascript:void(0);" :data-index="index">{{ item.title }}</a>
            </li>
        </ul>
      </div>
    </div>
    <div id="layout">
    </div>
    <login-dialog ref="loginDialog"></login-dialog>
  </div>
</template>

<script>
  function resizeEditor() {
    $("#layout").resize("100%");
    $(".CodeMirror-wrap").css({'width': '50%'});
    $(".editormd-preview").css({'width': '50%'});
  }

  function showPreview() {
      try {
          //testEditor.previewing();
          $(".markdown-body").appendTo($(".editormd-preview"));
          //$("#layout").hide();
          //$("#layout").remove();
      } catch (e) {
          setTimeout(function() {
              showPreview();
          }, 5);
      };
  }
  function isCollectTask(task) {
    var isCollect = false;
    if (task.tags && task.tags.length > 0) {
      var tags = task.tags;
      for(var i=0; i<tags.length; i++) {
        if (tags[i].key == 'save') {
          isCollect = true;
          break;
        }
      }
    }

    return isCollect;
  }

  var testEditor;
  import api from '../../api';
  import loginDialog from '../../components/all/login.vue';
  import headerNav from '../../components/all/header.vue';
  import '../../../static/z39pc/js/jquery-2.1.0.js';
  import { getDayMD } from '../../../static/jslib/parsetlog_common.js';
  import { mixinPc } from "../../common/mixinPc";

  $.ajaxSetup({
      xhrFields: {
        withCredentials: true
     }
  });

  export default{
    name:'dateLine',
    data(){
      return{
        apiHost: 'http://d7game.free.ngrok.cc',
        currentTab: 'first',
        day: '',
        month: '',
        week: '',
        searchTxt: '',
        token: '',
        compacted: false,
        weekTaskList: [],
        searchTaskList: [],
        collectedTaskList: [],
        cartTaskList: [],
        currentTasks: [
        ],
        selectedTasks: [

        ]
      }
    },
    components: {
      'header-nav':headerNav,
      'login-dialog': loginDialog
    },
    mixins: [mixinPc],
    computed:{
    },
    watch:{
    },
    methods:{
      showLoginDialog: function() {
        this.$refs.loginDialog.loginDialogVisible = true;
      },
      checkLogin:function(){
        api.checkLogin({}).then(data=>{
            if(data.errno!=0){
            this.$store.commit({ type: "reset" });
            localStorage.removeItem('timeUserInfo');
            localStorage.removeItem('tagTmpSortArr');
            this.timeUserInfo=''
            }
        });
      },
      handleClick(tab, event) {
        var that = this;
        switch (that.currentTab) {
          case 'first':
            that.currentTasks = that.weekTaskList;
            break;
          case 'second':
            that.currentTasks = that.searchTaskList;
            break;
          case 'third':
            that.currentTasks = that.collectedTaskList;
            break;
          case 'fourth':
            that.currentTasks = that.cartTaskList;
            break;
          default:
            break;
        }
      },
      closeOpen(e) {
        var $target   = $(e.target);
        var $taskWrap = $(".task-wrap");
        var $selWrap  = $(".sel-task-wrap");
        var $layout   = $("#layout");
        if (!$taskWrap.hasClass('hidden')) {
          $taskWrap.addClass('hidden');
          //$selWrap.addClass('hidden');
          $layout.css({'margin-left': '215px'});
          var $t = $target[0].tagName == 'A' ? $target.find("i") : $target;
          $t.removeClass('el-icon-d-arrow-left').addClass('el-icon-d-arrow-right');
        } else {
          $taskWrap.removeClass('hidden');
          $layout.css({'margin-left': '430px'});
          var $t = $target[0].tagName == 'A' ? $target.find("i") : $target;
          $t.removeClass('el-icon-d-arrow-right').addClass('el-icon-d-arrow-left');
        }
        resizeEditor();
      },
      putTasks() {
        var that = this;
        var ts = that.selectedTasks;
        console.log("selectedTasks:", ts);

        var md = getDayMD([{name:"",desc:"",tasks: ts}], false);
        //console.log(md);
        testEditor.setMarkdown(md);

        //$(".sel-task-wrap").addClass('hidden');
        //$("#layout").css({'margin-left': '230px'});
      },
      initEditor() {
        var that = this;
        var m = document.createElement('script');
        m.src = "/static/jslib/editormd.js";
        document.body.appendChild(m);
        m.onload = function() {
          var md = "";
          testEditor = editormd("layout", {
              width: "100%",
              height: 740,
              path: '/static/lib/',
              previewTheme: "dark",
              editorTheme: "pastel-on-dark",
              markdown: md,
              codeFold: true,
              //syncScrolling : false,
              saveHTMLToTextarea: true, // 保存 HTML 到 Textarea
              searchReplace: true,
              //watch : false,                // 关闭实时预览
              htmlDecode: "style,script,iframe|on*",
              emoji: true,
              taskList: true,
              tocm: true, // Using [TOCM]
              tex: true, // 开启科学公式TeX语言支持，默认关闭
              flowChart: true, // 开启流程图支持，默认关闭
              sequenceDiagram: true, // 开启时序/序列图支持，默认关闭,
              imageUpload: true,
              imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
              imageUploadURL: "./php/upload.php",
              mind: true,
              onload: function() {
                  console.log('onload', this);
              },
              toolbarIconsClass : {
                  saveBlog: "fa-save"  // 指定一个FontAawsome的图标类
              },
              lang : {
                  toolbar : {
                      saveBlog: "保存博客",
                  }
              },
              // 自定义工具栏按钮的事件处理
              toolbarHandlers : {
                  /**
                   * @param {Object}      cm         CodeMirror对象
                   * @param {Object}      icon       图标按钮jQuery元素对象
                   * @param {Object}      cursor     CodeMirror的光标对象，可获取光标所在行和位置
                   * @param {String}      selection  编辑器选中的文本
                   */
                  saveBlog : function(cm, icon, cursor, selection) {
                    var md = this.getMarkdown();
                    //console.log(md);
                    var uinfo = JSON.parse(localStorage.getItem('timeUserInfo'));
                    var $html = $(".markdown-body");
                    var $h1 = $html.find("h1");
                    if ($h1.length == 0) {
                      $h1 = $html.find("h3");
                    }
                    var btitle = $h1[0].textContent;
                    var bdesc = $html.find("p")[0].textContent.substring(0, 50);

                    api.blogAdd({
                      type: 5,
                      title: btitle,
                      desc: bdesc,
                      content: md,
                      url: ""
                    }).then(function(data){
                      if (typeof data == 'string') {
                        data = JSON.parse(data);
                      }
                      if (data.errno == 0) {
                        that.$message("保存成功");
                      } else {
                        that.$message("保存失败:" + data.errmsg);
                      }
                    });
                  }
              }
          });
          showPreview();
        };
      },
      login(loginInfo) {
          var that = this;
          return new Promise((resolve, reject) => {
              //调用登录接口
              $.ajax({
                  url: that.apiHost + '/center/public/loginmob',
                  type: 'POST',
                  contentType: "application/json",
                  dataType: "json",
                  data: JSON.stringify(loginInfo),
                  success: function(data) {
                      that.token = data.data.token;
                      $.ajaxSetup({
                        headers: {
                          Cookie: 'thinkjs=' + data.data.thinkjs,
                        }
                      });
                      resolve(true)
                  }
              })
          });
      },
      getWeekTasks() {
        var that = this;
        var date = new Date(that.day);
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        var d = date.getDate();
        var day = [y,m<10 ? '0' + m : m].join('-');
        api.tasksGet({'key': 'due:'+day}).then(function(data){
          console.log("getWeekTasks:", data);
          var d = data.data;
            if (!d.tasks || d.tasks.length == 0) {
              that.$message('未找到相关任务');
            }
            that.weekTaskList = d.tasks || [];
            that.currentTasks = that.weekTaskList;
            var ctasks = that.weekTaskList.filter(function(task){return isCollectTask(task);});
            that.collectedTaskList = ctasks;
        });
      },
      searchTasks() {
        var that = this;
        api.taskGet({content: that.searchTxt}).then(function(data){
            console.log("searchTasks", data);
            var d = data.data;
            if (!d || d.length == 0) {
              that.$message('未找到相关任务');
            }
            that.searchTaskList = d || [];
            that.currentTasks = that.searchTaskList;
            var ctasks = that.searchTaskList.filter(function(task){return isCollectTask(task);});
            that.collectedTaskList = ctasks;
        });
      },
      getBlog(bid) {
        var that = this;
        $.ajax({
          url: that.apiHost + '/api/z39blog?id=' + bid,
          type: 'GET',
          dataType: "json",
          success: function(data) {
            console.log("getBlog", data);
          }
        });
      }
    },
    mounted(){
      console.log("mounted");
      var that = this;
      this.checkLogin();

      this.initEditor();

      var taskSrc = $("#src-task-list")[0];
      var taskSel = $("#sel-task-list")[0];

      taskSrc.ondragstart = function(e){
        console.log(e);
        var transfer = e.dataTransfer;
        transfer.effectAllowed = "copy";
        transfer.setData("text/plain", e.target.getAttribute("data-index"));
        console.log("data-index=", e.target.getAttribute("data-index"));

        console.log("dragstart");
        $(".sel-task-wrap").removeClass('hidden');
        $("#layout").css({'margin-left': '430px'});

        return true;
      };
      taskSel.ondragenter = function(e) {
        e.preventDefault();
        e.stopPropagation();
        console.log("dragenter");
        return false;
      };
      taskSel.ondragover = function(e) {
        e.preventDefault();
        e.stopPropagation();
        console.log("dragiver");
        return false;
      };
      taskSel.ondrop = function(e) {
        e.preventDefault();
        e.stopPropagation();
        console.log("drop");
        var transfer = e.dataTransfer;
        transfer.dropEffect = "move";
        var i = parseInt(transfer.getData("text/plain"));
        console.log("i=", i);

        that.selectedTasks.push(that.currentTasks[i]);
        that.currentTasks.splice(i, 1);

        return false;
      };

      taskSrc.ondragend = function(e) {
        e.preventDefault();
        e.stopPropagation();
        console.log("dragend");
        return false;
      };

      taskSel.ondragstart = function(e){
        console.log(e);
        var transfer = e.dataTransfer;
        transfer.effectAllowed = "copy";
        transfer.setData("text/plain", e.target.getAttribute("data-index"));
        console.log("data-index=", e.target.getAttribute("data-index"));

        console.log("dragstart");
        return true;
      };
      taskSrc.ondragenter = function(e) {
        e.preventDefault();
        e.stopPropagation();
        console.log("dragenter");
        return false;
      };
      taskSrc.ondragover = function(e) {
        e.preventDefault();
        e.stopPropagation();
        console.log("dragiver");
        return false;
      };
      taskSrc.ondrop = function(e) {
        e.preventDefault();
        e.stopPropagation();
        console.log("drop");
        var transfer = e.dataTransfer;
        transfer.dropEffect = "move";
        var i = parseInt(transfer.getData("text/plain"));
        console.log("i=", i);

        that.currentTasks.push(that.selectedTasks[i]);
        that.selectedTasks.splice(i, 1);

        return false;
      };
      taskSel.ondragend = function(e) {
        e.preventDefault();
        e.stopPropagation();
        console.log("dragend");
        return false;
      };

      $("#close-sel").click(function(){
        $(".sel-task-wrap").addClass('hidden');
        $("#layout").css({'margin-left': '230px'});
      });
    }
  }
</script>

<style>
    #wrapper {
        display: flex;
        transition: all linear 0.3s;
    }
    #task-src {
        display: flex;
        position: fixed;
        left: 0;
        height: 100%;
        transition: all linear 0.2s;
    }
    #btn-show-selwrap {

    }
    .task-wrap {
      width: 210px;
      height: 100%;
      display: inline-block;
      float: left;
    }
    .src-task-wrap {
      height: 100%;
    }
    .sel-task-wrap {
      width: 200px;
      height: 100%;
      display: inline-block;
      float: left;
      z-index: 10000;
    }
    #close-sel, #bt-switch, .bt-close-open {
      text-decoration:none;
      color: #333;
      font-size: 12px;
    }
    .bt-close-open {
      position: relative;
      top: 50%;
    }
    .hidden {
      display: none;
    }
    .sel-title-text {
      margin-left: 2px;
      height: 42px;
      line-height: 42px;
      border-bottom: solid 1px #ddd;
    }
    .task-list {
      width: 100%;
      max-height: 700px;
      height: 100%;
      overflow-y: auto;
    }

    #layout {
      margin-left: 215px;
      transition: all linear 0.5s;
    }
    .compacted {
      transform: translateX(-205px);
    }

    .el-tabs__header {
    }
    .el-tabs__content {
    }
    .el-tabs__nav {
      display: flex;

    }
    .el-tabs__item {
        width: 50px;
        padding: 0;
    }
    .el-input__icon+.el-input__inner {
      padding-left: 5px;
    }
    .task-item {
        width: 95%;
        margin: 0 auto;
    }
    .task-item a{
        display: inline-block;
        padding: 8px;
        width: 100%;
        text-decoration: none;
        color: #000;
        text-align: left;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
    .checked {
      border: solid 1px #20a0ff;
      border-radius: 5px;
    }
    .task-item:nth-child(n+1) {
        border-bottom: solid 1px #ddd;
    }
    .task-item a:hover, .task-item a:active{
        background-color: #ddd;
    }
</style>